#include "ChromeManager.h"
#include "platform.h"


#define ENABLE_CHROME 1

#if ENABLE_CHROME == 1

#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "include/cef_client.h"
#pragma comment (lib, "libcef.lib")
#pragma comment (lib, "libcef_dll_wrapper.lib")

#include <mutex>
using namespace std;


class MyApp : public CefApp
{
	IMPLEMENT_REFCOUNTING(MyApp);
};
class MyHandler : public CefClient
{
	IMPLEMENT_REFCOUNTING(MyHandler);
	//IMPLEMENT_LOCKING(MyHandler);
};

unique_ptr<ChromeManager> ChromeManager::s_instance;
ChromeManager::ChromeManager(void)
{
}
ChromeManager::~ChromeManager(void)
{
}
ChromeManager& ChromeManager::instance()
{
	static mutex mx;
	if(!s_instance)
	{
		lock_guard<mutex> lock(mx);
		if(!s_instance)
		{
			s_instance.reset(new ChromeManager());
		}
	}
	return *s_instance;
}
void ChromeManager::startup(void* instance)
{
	CefMainArgs main_args(static_cast<HINSTANCE>(instance));
	CefRefPtr<MyApp> app(new MyApp);
	CefSettings settings;

	settings.multi_threaded_message_loop = true;
	settings.single_process = true;

	CefInitialize(main_args, settings, app.get());
}
void ChromeManager::shutdown()
{
	//SetErrorMode(SEM_NOGPFAULTERRORBOX);
	//CefShutdown();
}
void ChromeManager::create(void* host, const wstring& url)
{
	static CefRefPtr<MyHandler> handler = new MyHandler();

	CefWindowInfo info;
	CefBrowserSettings settings;

	RECT rect;
	GetClientRect(static_cast<HWND>(host), &rect);
	info.SetAsChild(static_cast<HWND>(host), rect);

	CefBrowserHost::CreateBrowser(info, handler.get(),
		url, settings, NULL);
}

#else

unique_ptr<ChromeManager> ChromeManager::s_instance;
ChromeManager::ChromeManager(void)
{
}
ChromeManager::~ChromeManager(void)
{
}
ChromeManager& ChromeManager::instance()
{
	if(!s_instance)
	{
		s_instance.reset(new ChromeManager());
	}
	return *s_instance;
}
void ChromeManager::startup(void* instance)
{
}
void ChromeManager::shutdown()
{
}
void ChromeManager::create(void* host, const wstring& url)
{
}
#endif
